package com.robot.member.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.member.pojo.vo.AuthorizationAccessToken;
import com.robot.member.pojo.vo.WeChatInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.IdWorker;
import util.JwtUtil;
import util.WeChatUtil;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wuyunbin
 */
@Service
public class WeChatService {

    @Autowired
    private MemberService memberService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    String errKey="errcode";
    /**
     * 获取 普通access_token
     * @return 普通access_token
     */
    public String getClientCredentialAccessToken() {
        //判断redis中是否有一个可用的token
        String key = "access_token";
        if (redisTemplate.hasKey(key)) {
            //如果有就直接返回
            String accessToken = redisTemplate.opsForValue().get(key);
            logger.info(accessToken);
            return redisTemplate.opsForValue().get(key);
        }
        //redis中没有可用的token则去微信获取一个
        String response= WeChatUtil.getClientCredentialAccessToken(appId,secret);

        logger.info(response);

        Map map = (Map) JSON.parse(response);
        //存储access_token到redis 微信标称有效期120分钟，取100分钟
        String accessToken = (String) map.get(key);
        redisTemplate.opsForValue().set("client_credential", accessToken, 100, TimeUnit.MINUTES);
        return accessToken;
    }

    /**
     * @param code 用户点击同意授权后 微信返回的code
     * @return 授权access_token
     */
    public AuthorizationAccessToken getAuthorizationAccessToken(String code) {
        logger.info(appId);
        logger.info(secret);
        logger.info(code);
        String response =WeChatUtil.getAuthorizationAccessToken(appId,secret,code);

        logger.info("response="+response);
        //如果包含错误

        if(response.contains(errKey)){
            logger.info(response);
            return null;
        }
        AuthorizationAccessToken authorizationAccessToken=JSONObject.parseObject(response,AuthorizationAccessToken.class);
        if(authorizationAccessToken!=null){
            logger.info(authorizationAccessToken.toString());
        }else{
            logger.info("authorizationAccessToken is null");
        }
        return authorizationAccessToken;
    }

    /**
     * 通过授权access_token和openId获取用户信息
     *
     * @param accessToken 授权access_token
     * @param openId      微信openId
     * @return 微信用户信息
     */
    public WeChatInfo getUserInfoByAuthorizationAccessTokenAndOpenId(String accessToken, String openId) {

        String response = WeChatUtil.getUserInfoByAuthorizationAccessTokenAndOpenId(accessToken,openId);
        logger.info(response);
        WeChatInfo weChatInfo=JSONObject.parseObject(response,WeChatInfo.class);
        logger.info(weChatInfo.toString());
        return weChatInfo;
    }
}
